<template>
  <affix :label="this.$t('business.dealBusiness') + '-' + this.processBusinessName"
         :flagClass="flag === 'webchat' ? 'webchat-affix':''"
         :showTitle="showTitle"
  >
    <main class="approval-form">
      <base-form :items="items"
                    ref="stepFields"
                   @cacheFields="cacheFields"
                   @showBigImg="showBigImg">
       </base-form>
      <el-form label-width="100px"
               :model="form"
               ref="form"
               :rules="rules"
      >
        <div>
          <el-form-item
                        :label="$t('business.nextMaster')"
                        v-if="isShow"
                        prop="master">
            <!--<span class="next-deal">{{$t('business.nextMaster')}}&nbsp;&nbsp;</span>-->
            <el-select size="mini" v-model.trim="form.master" :placeholder="$t('public.pleasePick')"  filterable @change="changeNextMaster">
              <el-option
                v-for="item in dealAgent"
                :label="item.label"
                :key="item.value"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <div class="wrapper">
            <el-button v-if="!batch" @click.stop="actionTemp" class="primary_btn" :disabled="disabledBtn">{{this.$t('business.staging')}}</el-button>
            <el-button type="primary" @click.stop="submit" class="primary_btn" :disabled="disabledBtn">{{this.$t('business.excuteAction')}}</el-button>
          </div>
        </div>
      </el-form>
    </main>
  </affix>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import {getCache} from '@/utils/m7Utils.js'
  import { commitImgType2 } from '@/utils/publicMethod.js'
  import {formRollToFirstError} from '@/utils/validate.js'
  import BaseForm from './base/BaseForm'
  import {getFlowStepActionById, getObjectById, getBusinessStepActionName, getStepRoles, getStepQueues, getQueueAgents, getRoleAgents} from '@/utils/workflowUtils.js'
  export default {
    name: 'Approval',
    props: {
      process: Object,
      business: Object,
      flag: String,
      showTitle: {type: Boolean, default: true}, // 是否展示tittle
      batch: Boolean // 批量处理工单（特殊处理流转到工单处理人）
    },
    components: {
      BaseForm,
      affix
    },
    data () {
      return {
        form: {
          _id: this.process._id,
          actionId: this.process.actionId,
          master: '',
          type: ''
        },
        isShow: true,
        items: [],
        disabledBtn: false,
        dealAgent: [],
        rules: {
          master: [
            {required: true, message: this.$t('business.masterRequierd'), trigger: 'change'}
          ]
        },
        stepCacheCurId: ''    //  当前动作stepcache id
      }
    },
    watch: {
      process (newV, oldV) {
        this.items = []
        this.$nextTick(() => {
          this.createProcessBusiness()
        })
      }
    },
    computed: {
      processBusinessName () {
        return getBusinessStepActionName(this.process.stepId, this.process.actionId)
      }
    },
    methods: {
      showBigImg (data) {
        // 获取所有包含imgA的图片
        let _array = this.$el.querySelectorAll('.approval-form .imgA')
        commitImgType2(data, _array)
      },
      changeNextMaster (value) {
        this.form.master = value
      },
      async createProcessBusiness () {
        if (!this.process.actionId) {
          return
        }
        let busCache = this.$getCache('busCache')
        let cacheId = this.process._id && (this.process._id + 'action')
        let currentStepCache = busCache[cacheId] || {}
        // 获取该工单的动作缓存，如果actionId不相同，则初始化工单动作缓存
        if (cacheId && currentStepCache.actionId !== this.process.actionId) {
          busCache[cacheId] = {actionId: this.process.actionId}
        }
        // 重新获取当前步骤缓存
        currentStepCache = busCache[cacheId] || {}
        let flow = getCache('businessFlow', this.process.flow)
        let step = getCache('businessFlowStep', this.process.stepId)
        let action = getFlowStepActionById(step.actions, this.process.actionId) || {}
        // specific为true 指定当前处理人
        this.rules.master[0].required = action.specific || false
        this.form = {
          _id: this.business._id,
          actionId: this.process.actionId,
          master: ''
        }
        // 定义客户字段顺序
        this.items = action.actionFields || []
        // 客户字段，定义内容样式
        let flowFields = flow ? flow.fields : []
        for (let i = 0; i < this.items.length; i++) {
          let row = this.items[i]
          for (let j = 0; j < row.cols.length; j++) {
            let col = row.cols[j]
            for (let k = 0; k < col.fields.length; k++) {
              let field = col.fields[k]
              let cacheField = getObjectById(flowFields, field._id)
              // 取数据的优先级是缓存>工单中的>defualt
              if (cacheField.type === 'dropdown' || cacheField.type === 'dropdownTree') {
                cacheField['default'] = ['', '', '', '', ''].map((item, index) => {
                  return !index ? (currentStepCache[cacheField._id] ||
                    this.business[cacheField._id] ||
                    cacheField['default'])
                    : (currentStepCache[cacheField._id + `_${index}`] ||
                      this.business[cacheField._id + `_${index}`] || '')
                })
              } else if (cacheField.type === 'checkbox') {
                cacheField['default'] = currentStepCache[cacheField._id] ||
                  this.business[cacheField._id] ||
                  [cacheField['default']]
              } else {
                cacheField['default'] = currentStepCache[cacheField._id] ||
                  this.business[cacheField._id] ||
                  cacheField['default']
              }
              Object.assign(field, cacheField)
            }
          }
        }
        //    工单暂存 回显暂存的 动作  start   ========================
        let stepCache = this.business.stepCache ? this.business.stepCache : false
        let stepCacheCur = {}    //  当前动作下的  数据
        if (stepCache) {
          for (let i = 0; i < stepCache.length; i++) {
            if (this.process.actionId === stepCache[i].actionId) {
              stepCacheCur = stepCache[i]
            }
          }
        }
        this.stepCacheCurId = ''
        if (stepCacheCur.actionId) {    //   如果当前动作有暂存数据
          this.stepCacheCurId = stepCacheCur._id
          this.items.forEach(item => {
            item.cols.forEach(one => {
              one.fields.forEach(the => {
                  if (the.type === 'dropdown' || the.type === 'dropdownTree') {
                  the.default = []
                  let well = stepCacheCur[the._id] || ''
                  let well1 = stepCacheCur[the._id + '_1'] || ''
                  let well2 = stepCacheCur[the._id + '_2'] || ''
                  let well3 = stepCacheCur[the._id + '_3'] || ''
                  let well4 = stepCacheCur[the._id + '_4'] || ''
                  the.default = [well, well1, well2, well3, well4]
                } else {
                  for (let key in stepCacheCur) {
                    if (the._id === key) {
                      the.default = stepCacheCur[key]
                    }
                  }
                }
              })
            })
          })
        }
        //    工单暂存 回显暂存的 动作  end   ========================
        let nextStepId = action.jumpTo
        let nextStep = getCache('businessFlowStep', nextStepId)
        if (nextStep.type === 'sys') {
          this.nextStepValue = 'sys'
          this.isShow = false
        } else {
          this.isShow = true
          let roles = getStepRoles(nextStepId)
          let queues = getStepQueues(nextStepId)
          let queueAgents = []
          let roleAgentList = []
          let queueAgentList = []
          roleAgentList = getRoleAgents(roles, true, this.business.createUser)
          queueAgentList = await getQueueAgents(queues, true)
          let agents = [...new Set(roleAgentList.concat(queueAgentList))]
          this.dealAgent = []
          if (roles.length === 1 && roles[0] === 'busCreateUser') {
            if (this.batch) {
              // 如果是批量处理下一步流转到工单创建人，下一步处理人master标识下
              this.form.master = 'createUser'
              this.isShow = false
              return
            }
          } else {
            if (agents.length !== 1) {
              this.dealAgent.push({label: this.$t('public.autoAssign'), value: ''})
            }
          }
          for (let i = 0; i < agents.length; i++) {
            this.dealAgent.push({label: agents[i].displayName, value: agents[i]._id})
          }
//          if (agents.length === 1) {
//            this.form.master = agents[0]._id
//          }
          if (nextStep.defaultAgent && this.dealAgent.length) {
            if (nextStep.defaultAgent === 'busCreateUser') {
              nextStep.defaultAgent = this.business.createUser
            }
            let defaultAgent = this.dealAgent.filter((item) => {
              if (item.value === nextStep.defaultAgent) {
                return true
              }
            })
            this.form.master = defaultAgent[0] ? defaultAgent[0].value : this.dealAgent[0].value
          } else {
            this.form.master = this.dealAgent[0] ? this.dealAgent[0].value : ''
          }
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
        }
      },
      // 缓存事件
      cacheFields (data) {
        let busCache = this.$getCache('busCache')
        let cacheId = this.process._id + 'action'
        if (busCache[cacheId]) {
          Object.assign(busCache[cacheId], data.data)
        }
      },
      submit () {
        let data = {}
        let stepFields = this.$refs.stepFields.submit()
        if (stepFields) {
          Object.assign(data, stepFields)
          this.excuteBusinessStepAction(data)
        } else { // 校验不通过
          formRollToFirstError(this.$refs.form.$el) // 表单校验有问题时，滚动到第一个el-error的位置
        }
      },
      excuteBusinessStepAction (data) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$emit('event', {event: 'stepAction', data: {_id: this.business._id, customer: this.business.customer, form: Object.assign(data, this.form)}})
          }
        })
      },
      //      暂存     =====================
      actionTemp () {
        let data = {}
        data._id = this.stepCacheCurId
        data.businessId = this.business._id
        data.step = this.business.step
        data.actionId = this.process.actionId
        let stepFields = this.$refs.stepFields.submit()
        if (stepFields) {
          Object.assign(data, stepFields)
          this.tempBusinessStepAction(data)
        } else { // 校验不通过
          formRollToFirstError(this.$refs.form.$el) // 表单校验有问题时，滚动到第一个el-error的位置
        }
      },
      tempBusinessStepAction (data) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$emit('event', {event: 'stepActionTemp', data: {_id: this.business._id, customer: this.business.customer, dataForm: data}})
          }
        })
      },
    },
    beforeMount () {
      this.createProcessBusiness()
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../../assets/common.styl'
  .approval
    padding 20px 0 0
    header
      text-align center
      padding 10px 0
      h3
        display inline-block
        color $cf-level2
    main
    &:before
      content ''
      clear both
  .wrapper
    text-align right
  .next-deal
    color $cf-level1
    font-size 12px
</style>
